﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Tool.Core
{
    public class ListOperation
    {
        public ListOperation()
        {

        }

        public ModelList GetByName(string name, List<ModelList> lists)
        {
            foreach (var item in lists)
            {
                if (name == item.Name)
                    return item;
            }
            return null;
        }

        public List<ModelList> GetAllListInfo()
        {
            List<ModelList> modelLists = new List<ModelList>();
            SPWeb adminWeb = Common.GetAdminWeb();
            SPListCollection lists = adminWeb.Lists;
            foreach (SPList list in lists)
            {
                string listName = list.Title;
                Guid guid = list.ID;

                SPFieldCollection fields = list.Fields;
                List<ModelField> allFields = new List<ModelField>();
                foreach (SPField f in fields)
                {

                    string internalName = f.InternalName;
                    if (Common.IsUnUserfullProperties(internalName))
                        continue;
                    string type = f.TypeAsString;

                    string title = f.Title;
                    allFields.Add(
                        new ModelField() { SPFieldType = type, DisplayName = title, InternalName = internalName });
                }
                modelLists.Add(new ModelList() { ListGuid = guid, Name = listName, AllFields = allFields.ToArray() });
            }

            return modelLists;
        }


        /// <summary>
        /// 删除列表里面的数据
        /// </summary>
        /// <param name="shouldDeleteLists"></param>
        /// <returns></returns>
        public static bool DeleteListInformation(List<ModelList> shouldDeleteLists)
        {
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
            SPWeb adminWeb = Common.GetAdminWeb();
            SPListCollection lists = adminWeb.Lists;
            foreach (SPList list in lists)
            {

                bool isDoc = list.BaseTemplate == SPListTemplateType.DocumentLibrary;
                Guid guid = list.ID;
                if (shouldDeleteLists.Contains(new ModelList() { ListGuid = guid }))
                {
                    SPQuery query = new SPQuery();
                    SPListItemCollection items = list.GetItems(query);
                    //  foreach (SPListItem item in list.Items)
                    foreach (SPListItem item in items)
                    {
                        sbDelete.Append("<Method>");
                        sbDelete.Append("<SetList Scope=\"Request\">" + list.ID + "</SetList>");
                        sbDelete.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
                        sbDelete.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                        if (isDoc)
                            sbDelete.Append("<SetVar Name=\"owsfileref\">" + item.GetFormattedValue("FileRef") + "</SetVar>");
                        sbDelete.Append("</Method>");
                    }
                }
            }
            sbDelete.Append("</Batch>");
            adminWeb.ProcessBatchData(sbDelete.ToString());
            return true;
        }


        /// <summary>
        /// 生产列表名称的Guid string
        /// </summary>
        /// <param name="lists"></param>
        /// <returns></returns>
        public static string GetListNameConsts(List<ModelList> lists)
        {
            StringBuilder sb = new StringBuilder();

            if (lists != null && lists.Count > 0)
            {
                sb.Append(Environment.NewLine);
                foreach (var item in lists)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(string.Format("\t public static readonly string {0} = \"{1}\";", item.Name.ReplacementByRegulation(), item.StrGuid));
                }
                sb.Append(Environment.NewLine);
            }
            return sb.ToString();
        }

        public static string GetModels(ModelList model)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in model.AllFields)
            {
                sb.Append(Environment.NewLine);

                sb.Append(string.Format("\t public {0} {1} ", item.NetTypeString, item.DisplayName));
                sb.Append("{set;get;}");
            }
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }

        public static string GetFieldConsts(ModelList model)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in model.AllFields)
            {
                sb.Append(Environment.NewLine);
                sb.Append(string.Format("\t public static readonly string {0} = \"{1}\"; ", item.DisplayName, item.InternalName));
            }
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }

        public static string GetBusinessAddInfo(ModelList model)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in model.AllFields)
            {
                if (item.DisplayName == "ID") continue;
                sb.Append(Environment.NewLine);
                sb.Append(string.Format("\t item[FieldsConst{0}.{1}] = model.{1}; ", model.Name, item.DisplayName));
            }
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }

        public static string GetBusinessUpdate(ModelList model)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in model.AllFields)
            {
                if (item.DisplayName == "ID") continue;
                sb.Append(Environment.NewLine);
                sb.Append(string.Format("\t if(model.{0} != null)", item.DisplayName));
                sb.Append(Environment.NewLine);
                sb.Append(string.Format("\t\t item[FieldsConst{0}.{1}] = model.{1}; ", model.Name, item.DisplayName));
            }
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }

        public static string GetChangeItemToModel(ModelList model)
        {
            //规则  所有的人员控件不论是 单个人员还是多个人员统一修改 多人
            StringBuilder sb = new StringBuilder();
            sb.Append(Environment.NewLine);
            sb.Append(string.Format("\t model.ID = ID;"));
            foreach (var item in model.AllFields)
            {
                if (item.DisplayName == "ID") continue;
                sb.Append(Environment.NewLine);

                if (item.NetTypeString == "string")
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.GetItemString(item[FieldsConst{0}.{1}]); ", model.Name, item.DisplayName));
                else if (item.NetTypeString == "bool?")
                {
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.GetItemBool(item[FieldsConst{0}.{1}]); ", model.Name, item.DisplayName));
                }
                else if (item.NetTypeString == "SPFieldUrlValue")
                {
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.GetItemSPFieldUrlValue(item[FieldsConst{0}.{1}]); ", model.Name, item.DisplayName));
                }else if (item.NetTypeString == "int?")
                {
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.GetItemInt(item[FieldsConst{0}.{1}]); ", model.Name, item.DisplayName));
                }
                else if (item.NetTypeString == "DateTime?")
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.GetItemDateTime(item[FieldsConst{0}.{1}]); ", model.Name, item.DisplayName));
                else if (item.SPFieldType == "User")
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.ChangeSPFieldUserValueTOUserCollection(item[FieldsConst{0}.{1}], adminWeb); ", model.Name, item.DisplayName));
                else if (item.NetTypeString == "SPFieldLookupValue")
                    sb.Append(string.Format("\t  model.{1}=new SPFieldLookupValue(SPListItemHelper.GetItemString(item[FieldsConst{0}.{1}])); ", model.Name, item.DisplayName));
                else if (item.NetTypeString == "SPFieldUserValueCollection")
                    sb.Append(string.Format("\t  model.{1}=item[FieldsConst{0}.{1}] as SPFieldUserValueCollection; ", model.Name, item.DisplayName));
                else if (item.NetTypeString == "")
                {
                    sb.Append(string.Format("\t  model.{1}=item[FieldsConst{0}.{1}] as SPFieldUserValueCollection; ", model.Name, item.DisplayName));
                }
                else
                    sb.Append(string.Format("\t  model.{1}=SPListItemHelper.GetItemString(item[FieldsConst{0}.{1}]); ", model.Name, item.DisplayName));

            }
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }



        public static bool CreateList(IList<ModelListCreator> lists)
        {
            SPWeb adminWeb = Common.GetAdminWeb();

            foreach (var item in lists)
            {
                try
                {
                    SPList list = adminWeb.Lists[item.Name];
                    if (list != null) list.Delete();

                }
                catch (Exception e)
                {   
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    adminWeb.Lists.Add(item.Name, item.Description, adminWeb.ListTemplates[item.TemplateName]);
                    SPList list = adminWeb.Lists[item.Name];
                    list.OnQuickLaunch = true;
                    list.Update();
                    SPFieldCollection fields = list.Fields;
                    CreateFields(fields, item);
                }
            }
            return true;
        }



        private static void CreateFields(SPFieldCollection fields, ModelListCreator model)
        {


            // show item in defalut view
            //SPView view = newList.DefaultView;
            //    view.ViewFields.Add("NewText");
            //    view.ViewFields.Add("NewLookup");
            //    view.Update();Z
            if (model != null && model.Fields != null)
            {
                foreach (var item in model.Fields)
                {
                    // Our definition for the CAML. Note that DisplayName is really our internal name here
                    string newField = "<Field Type=\"{0}\" DisplayName=\"{1}\" Name=\"{2}\" Description=\"{3}\" Required=\"{4}\" />";
                    newField = string.Format(newField, item.SPFieldType, item.DisplayName, item.InternalName, item.Description, item.Required);

                    // Call the SharePoint method to create the field.
                    fields.AddFieldAsXml(newField);

                    SPView view = fields.List.DefaultView;
                    view.ViewFields.Add(item.DisplayName);
                    view.Update();
                    //// Retrieve the newly created field using the internal nameSZZ
                    //SPField field = fields[internalName];

                    //// Reset the title to the name we want it to be (after AddFieldAsXml the display name will be the internal name)
                    //field.Title = displayName;

                    //// Finally commit the updates to the field
                    //field.Update();



                    // show item in defalut view


                }

            }



        }


    }
}
